package com.situ.blog.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCutil {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    private JDBCutil() throws ClassNotFoundException {

    }



    //导入配置文件


   static  {

       try {
           Properties properties = new Properties();
           //1.获得当前类的类加载器
           ClassLoader classLoader = JDBCutil.class.getClassLoader();
           //2.通过类加载器的getResourceAsStream方法，获取文件流
           InputStream inputStream = classLoader.getResourceAsStream("db.properties");
           //3.properties
           properties.load(inputStream);
           //4..properties文件是以键值对的方式加载的，根据key值导入value值
           driver = properties.getProperty("driver");
           url = properties.getProperty("url");
           username = properties.getProperty("username");
           password = properties.getProperty("password");
       } catch (IOException e) {
           throw new RuntimeException(e);
       }
       try {
           Class.forName(driver);
       } catch (ClassNotFoundException e) {
           throw new RuntimeException(e);
       }
   }

    public static Connection getConnection() throws SQLException {
        Connection connection = DriverManager.getConnection(url,username,password);
        return connection;
    }

    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
